package 链表.双链表求平均值;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/10/15 9:57
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        ListNode root = new ListNode(-1,new ListNode(2,new ListNode(4,new ListNode(6,new ListNode(8,null)))));
        insertMeanNode(root);
        resortList(root);
    }

    public static void insertMeanNode(ListNode root) {
        //ListNode * p = root -> next;
        ListNode p = root.next;
        //初始的链表值总和
        int sum = 0;
        //初始长度
        int len = 0;
        while (p != null) {
            //p -> data;
            sum += p.val;
            len++;
            p = p.next;
        }
        //平均值
        int mean = sum / len;
        /**
         * ListNode newNode = (molloc * ListNode).........
         * newNode -> data = mean;
         */
        ListNode newNode = new ListNode(mean);
        /**
         * 双链表需要替换代码
         */
        newNode.next = root.next;
        root.next = newNode;

    }

    //5 2 4 6 8

    public static void resortList(ListNode root) {
        //ListNode p = root -> next;
        ListNode p = root.next;
        ListNode pre = root;
        int mean = p.val;
        if (p.next != null) {
            pre = p;
            p = p.next;
        }
        while (p != null) {
            if (p.val < mean) {
                ListNode q = p.next;
                p.next = root.next;
                root.next = p;
                pre.next = q;
                p = q;
            } else {
                pre = p;
                p = p.next;
            }
        }
        System.out.println("  ");
    }

}
